<?php

namespace App\Http\Controllers\AgentAdmin;

use App\Enums\MessagePublishStatus;
use App\Http\Controllers\Controller;
use App\Models\AgentUser;
use App\Models\FrontendUser;
use App\Models\MessageReceiver;
use App\Models\MessageTemplate;
use App\Models\Notice;
use App\Utils\UploadHelper;
use Illuminate\Support\Arr;
use Vinlon\Laravel\LayAdmin\Exceptions\AdminException;

class MessageController extends Controller
{
    /**
     * BannerController constructor.
     */
    public function __construct()
    {
    }

    /** 上传接收人列表 */
    public function uploadReceivers()
    {
        /** @var AgentUser $user */
        $user = auth()->user();
        $data = UploadHelper::readExcel(request()->file('file'));

        // 检查文件头和是否有数据
        $header = array_slice($data[0], 0, 4);
        unset($data[0]);
        if ($header != ['接收人手机号', 'keyword1', 'keyword2', 'keyword3']) {
            throw new AdminException('文件头错误，请使用指定模板上传');
        }
        if (0 == count($data)) {
            throw new AdminException('文件中不包含数据');
        }
        if (count($data) > 2000) {
            throw new AdminException('每次最多发送给2000人');
        }

        //检查是否上传keyword
        $firstRow = $data[1];
        $hasKeyword1 = '' != $firstRow[1];
        $hasKeyword2 = '' != $firstRow[2];
        $hasKeyword3 = '' != $firstRow[3];

        //检查重复手机号
        $mobiles = [];
        foreach ($data as $row) {
            $mobile = (int) $row[0];
            if (in_array($mobile, $mobiles)) {
                throw new AdminException('手机号' . $mobile . '重复');
            }
            $mobiles[] = $mobile;
        }
        $uploadSn = uniqid();
        while (true) {
            $rows = array_splice($data, 0, 1000);
            if (0 === count($rows)) {
                break;
            }
            $batchValues = [];
            $batchMobiles = [];
            foreach ($rows as $index => $row) {
                $mobile = (int) $row[0];
                $batchMobiles[] = $mobile;
                $keyword1 = $row[1];
                $keyword2 = $row[2];
                $keyword3 = $row[3];

                $batchValues[] = [
                    'created_at' => now(),
                    'updated_at' => now(),
                    'upload_sn' => $uploadSn,
                    'template_id' => 0,
                    'keyword1' => $keyword1,
                    'keyword2' => $keyword2,
                    'keyword3' => $keyword3,
                ];
            }
            $userIdMap = FrontendUser::query()
                ->where('agent_id', $user->agent_id)
                ->whereIn('mobile', $batchMobiles)
                ->orderByDesc('id')
                ->get()->mapWithKeys(function (FrontendUser $user) {
                    return [$user->mobile => $user->id];
                });
            foreach ($batchMobiles as $index => $mobile) {
                $userId = Arr::get($userIdMap, $mobile);
                if (!$userId) {
                    throw new AdminException('手机号' . $mobile . '对应的用户未找到');
                }
                $batchValues[$index]['receiver_id'] = $userId;
            }
            MessageReceiver::query()->insert($batchValues);
        }

        return [
            'upload_sn' => $uploadSn,
            'has_keyword1' => $hasKeyword1,
            'has_keyword2' => $hasKeyword2,
            'has_keyword3' => $hasKeyword3,
        ];
    }

    /** 查询站内信模板列表 */
    public function listTemplates()
    {
        /** @var AgentUser $user */
        $user = auth()->user();

        $query = MessageTemplate::query()
            ->where('agent_id', $user->agent_id)
            ->withCount(['messages'])
            ->orderByDesc('id');

        return paginate_result($query);
    }

    /** 保存站内信模板 */
    public function saveTemplate()
    {
        /** @var AgentUser $user */
        $user = auth()->user();

        $params = request()->validate([
            'upload_sn' => 'required',
            'title' => 'required',
            'content' => 'required',
            'publish_time' => 'nullable',
        ]);
        $uploadSn = Arr::get($params, 'upload_sn');
        Arr::forget($params, 'upload_sn');
        $params = Arr::add($params, 'publish_time', now());

        $template = new MessageTemplate();
        $template->agent_id = $user->agent_id;
        $template->fill($params);
        $template->save();

        //更新receivers中的template_id
        MessageReceiver::query()
            ->where('upload_sn', $uploadSn)
            ->update([
                'template_id' => $template->id,
            ]);
    }

    /** 删除站内信模板 */
    public function deleteTemplate($id)
    {
        /** @var MessageTemplate $template */
        $template = MessageTemplate::query()->find($id);
        //删除MessageTemplate
        if ($template->publish_status->is(MessagePublishStatus::PUBLISHING)) {
            throw new AdminException('消息发送中，请稍后再删除');
        }
        \DB::transaction(function () use ($template) {
            $template->delete();
            //删除MessageReceiver
            MessageReceiver::query()->where('template_id', $template->id)->delete();
            //删除Notice
            Notice::query()->where('template_id', $template->id)->delete();
        });
    }
}
